import Router from '@koa/router';
import ArticleStat from '../models/ArticleStat.js';
// 在中间件中使用队列
import Queue from 'bull';
const viewQueue = new Queue('article_views');

const router = new Router({ prefix: '/stats' });

// 获取文章统计数据
router.get('/articles/:id', async ctx => {
  const stat = await ArticleStat.findOne({
    where: { article_id: ctx.params.id },
    attributes: ['view_count', 'last_viewed_at']
  });

  ctx.body = {
    code: 0,
    data: stat || { view_count: 0, last_viewed_at: null }
  };
});

// 获取热门文章
router.get('/articles/hot', async ctx => {
  const limit = Math.min(parseInt(ctx.query.limit) || 10, 100);

  const stats = await ArticleStat.findAll({
    order: [['view_count', 'DESC']],
    limit,
    attributes: ['article_id', 'view_count']
  });

  ctx.body = { code: 0, data: stats };
});

export default router;